using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using System.Security.Claims;
using System.Linq;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 媒体文件管理接口
    /// 提供媒体文件的上传、管理、删除等功能的 RESTful API
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class MediaController : ControllerBase
    {
        private readonly IMediaFileAppService _mediaService;
        private readonly ILogger<MediaController> _logger;

        public MediaController(
            IMediaFileAppService mediaService,
            ILogger<MediaController> logger)
        {
            _mediaService = mediaService;
            _logger = logger;
        }

        /// <summary>
        /// 分页获取媒体文件列表
        /// </summary>
        /// <returns>媒体文件分页结果</returns>
        [HttpGet]
        [ProducesResponseType(200)]
        public async Task<ActionResult<PagedResultDto<MediaFileDto>>> GetPaged(
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 20,
            [FromQuery] string? keyword = null,
            [FromQuery] string? category = null,
            [FromQuery] string? fileType = null,
            [FromQuery] byte? status = null)
        {
            try
            {
                var (items, total) = await _mediaService.GetPagedAsync(pageIndex, pageSize, keyword, category, fileType, status);
                return Ok(new PagedResultDto<MediaFileDto>(items, total, pageIndex, pageSize));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting paged media files");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpGet("all")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<IEnumerable<MediaFileDto>>> GetAll()
        {
            try
            {
                var items = await _mediaService.GetAllAsync();
                return Ok(items);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting all media files");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpGet("{id:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        public async Task<ActionResult<MediaFileDto>> GetById(long id)
        {
            try
            {
                var item = await _mediaService.GetByIdAsync(id);
                if (item == null) return NotFound();
                return Ok(item);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting media file {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpGet("by-path")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<MediaFileDto?>> GetByPath([FromQuery] string filePath)
        {
            try
            {
                var item = await _mediaService.GetByFilePathAsync(filePath);
                return Ok(item);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting media by path");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpGet("by-hash")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<MediaFileDto?>> GetByHash([FromQuery] string hash)
        {
            try
            {
                var item = await _mediaService.GetByHashAsync(hash);
                return Ok(item);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting media by hash");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpGet("category/{category}")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<IEnumerable<MediaFileDto>>> GetByCategory(string category)
        {
            try
            {
                var items = await _mediaService.GetByCategoryAsync(category);
                return Ok(items);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting media by category {Category}", category);
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpGet("type/{fileType}")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<IEnumerable<MediaFileDto>>> GetByFileType(string fileType)
        {
            try
            {
                var items = await _mediaService.GetByFileTypeAsync(fileType);
                return Ok(items);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting media by type {Type}", fileType);
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpPost("upload")]
        [RequestSizeLimit(104_857_600)]
        [ProducesResponseType(200)]
        public async Task<ActionResult<MediaFileDto>> Upload([FromForm] IFormFile file, [FromForm] string? category = null, [FromForm] string? title = null, [FromForm] string? description = null, [FromForm] string? alt = null)
        {
            try
            {
                var item = await _mediaService.UploadAsync(file, category, title, description, alt);
                return Ok(item);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error uploading media file");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpPost("batch-upload")]
        [RequestSizeLimit(209_715_200)]
        [ProducesResponseType(200)]
        public async Task<ActionResult<IEnumerable<MediaFileDto>>> BatchUpload([FromForm] List<IFormFile> files, [FromForm] string? category = null)
        {
            try
            {
                var items = await _mediaService.BatchUploadAsync(files, category);
                return Ok(items);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error batch uploading media files");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 创建媒体文件记录
        /// </summary>
        /// <param name="dto">媒体文件数据</param>
        /// <returns>创建的媒体文件</returns>
        [HttpPost]
        [ProducesResponseType(201)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<MediaFileDto>> Create([FromBody] MediaFileDto dto)
        {
            try
            {
                var created = await _mediaService.CreateAsync(dto);
                return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating media file record");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpPut("{id:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<MediaFileDto>> Update(long id, [FromBody] MediaFileDto dto)
        {
            try
            {
                dto.Id = id;
                var updated = await _mediaService.UpdateAsync(dto);
                return Ok(updated);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating media file {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpDelete("{id:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        public async Task<ActionResult<object>> Delete(long id, [FromQuery] bool deletePhysicalFile = true)
        {
            try
            {
                var ok = await _mediaService.DeleteAsync(id, deletePhysicalFile);
                if (!ok) return NotFound();
                return Ok(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting media file {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpPost("batch-delete")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> BatchDelete([FromBody] BatchDeleteRequest request, [FromQuery] bool deletePhysicalFiles = true)
        {
            try
            {
                var count = await _mediaService.BatchDeleteAsync(request.Ids, deletePhysicalFiles);
                return Ok(new { success = true, count });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error batch deleting media files");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpPost("{id:long}/status")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> UpdateStatus(long id, [FromQuery] byte status)
        {
            try
            {
                var ok = await _mediaService.UpdateStatusAsync(id, status);
                return Ok(new { success = ok });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating media status {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpPost("{id:long}/downloads/increment")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> IncrementDownload(long id)
        {
            try
            {
                var ok = await _mediaService.IncrementDownloadCountAsync(id);
                return Ok(new { success = ok });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error incrementing download count {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpPost("{id:long}/thumbnail")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> GenerateThumbnail(long id, [FromQuery] int width = 150, [FromQuery] int height = 150)
        {
            try
            {
                var url = await _mediaService.GenerateThumbnailAsync(id, width, height);
                return Ok(new { url });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error generating thumbnail for {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpGet("search")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<PagedResultDto<MediaFileDto>>> Search([FromQuery] string keyword, [FromQuery] int pageIndex = 1, [FromQuery] int pageSize = 20)
        {
            try
            {
                var (items, total) = await _mediaService.SearchAsync(keyword, pageIndex, pageSize);
                return Ok(new PagedResultDto<MediaFileDto>(items, total, pageIndex, pageSize));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error searching media files");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpGet("stats")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> Stats()
        {
            try
            {
                var stats = await _mediaService.GetStorageStatisticsAsync();
                return Ok(stats);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting storage statistics");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpPost("cleanup-unused")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> CleanupUnused()
        {
            try
            {
                var count = await _mediaService.CleanupUnusedFilesAsync();
                return Ok(new { success = true, count });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error cleaning up unused media files");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpGet("{id:long}/url")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<object>> GetUrl(long id, [FromQuery] int? expireMinutes = null)
        {
            try
            {
                var url = await _mediaService.GetFileUrlAsync(id, expireMinutes);
                return Ok(new { url });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting file url {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }
    }
}
